const libK = require("../lib").libKDocsDrive;
const path = require("path");
const fs = require("fs");
// const path = require("path");
const FormData = require("form-data");
const Toolbox = require("../tool/toolbox");
const jexcel = require('json2excel');
// const xlsx = require('node-xlsx');
const XLSX = require("xlsx");

const CombinedStream = require('combined-stream');
// let kdoc = new libK.KdocsDrive('V02SM4K7yqLwAoUXAhCzMtMvNDDkGRQ00a10b3320029d3cb62');
let kdoc = new libK.KdocsDrive('V02SJuD-whLCRLjGvhRvzt-XML7uqlw00a146fce003d18ab1d');
const rs = require("randomstring");

kdoc.ONLY_ONCE_getSpecialGroupInfo().then(async o => {
  var hiroTakeiBook = XLSX.readFile(path.join(__dirname,"../tmp/hirorotakei.xlsx"));
  var hiroroBook = XLSX.readFile(path.join(__dirname,"../tmp/hiroro.xlsx"));
  
  debugger


  let wb = XLSX.utils.book_new();
  let ws_data = [
    ["S", "h", "e", "e", "t", "J", "S"],
    [1, 2, 3, 4, 5]
  ];
  let ws = XLSX.utils.aoa_to_sheet(ws_data);
  XLSX.utils.book_append_sheet(wb, ws, "sheetjs");
  XLSX.writeFile(wb, path.join(__dirname, "../tmp/shhet.xlsx"), {
    compression: false
  })
  debugger
  let sp = o.data.special_group;
  const KDFILE_ROOT = 77723428716

  let upload0717 = (filepath, filename) => new Promise(async resolve => {
    let o_token = await sp.getKs3Token(filename);
    debugger
    let cStream = CombinedStream.create();
    let f1 = fs.createReadStream(path.join(__dirname, "../tmp/2015-05-20-A001.psd"), {
      end: 1024 * 1024//bytesRead将是1025
    });
    let f2 = fs.createReadStream(filepath);
    let sizeOf2 = (await Toolbox.getStats(filepath)).stats.size;
    cStream.append(f1);
    cStream.append(f2);

    let form = new FormData();
    form.append("key", o_token.data.key);
    form.append("Policy", o_token.data.Policy);
    form.append("submit", "Upload to KS3");
    form.append("Signature", o_token.data.Signature);
    form.append("KSSAccessKeyId", o_token.data.KSSAccessKeyId);
    form.append("x-kss-newfilename-in-body", o_token.data["x-kss-newfilename-in-body"]);
    form.append("x-kss-server-side-encryption", o_token.data["x-kss-server-side-encryption"]);
    form.append("file", cStream, {
      filename: "abcd.psd",
      contentType: "application/octet-stream",
      knownLength: 1024 * 1024 + 1 + sizeOf2
    });

    let url = require("url");
    let using_url = o_token.data.url
    let parsed = url.parse(using_url);
    form.submit({
      host: parsed.host,
      path: parsed.path,
      headers: {
        Origin: 'https://www.kdocs.cn',
        Referer: 'https://www.kdocs.cn/mine/77723428716',
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"
      },
      protocol: parsed.protocol
    }, async (err, response) => {
      debugger
      let etag = response.headers.etag;
      let newfilename = response.headers.newfilename;
      let o_file = await sp.createFile_newfile(KDFILE_ROOT, filename, newfilename,
        etag, 1024 * 1024 + 1 + sizeOf2);
      debugger
      resolve();
    })
  });
  await upload0717(path.join(__dirname,"../tmp/Z.wim.001"),"Z1.wim.001");
  await upload0717(path.join(__dirname,"../tmp/Z.wim.002"),"Z1.wim.002");
  // await upload0717(path.join(__dirname,"../tmp/Z.7z.003"),"Z1.7z.003");
  // await upload0717(path.join(__dirname,"../tmp/TT.part2.rar"),"TT1.part2.rar");
  debugger


  // f1.pipe(process.stdout);
  // f1.on("end",()=>{
  //   f1.bytesRead;
  //   debugger
  // })
  // let o_try = await listLargeFile(KDFILE_ROOT);


  /**
   * 
   * @param {Number} folder_id 
   */
  function listLargeFile(folder_id) {
    return new Promise(async resolve => {
      let page = 0;
      while (true) {
        let o_list = await sp.listDownloadableItemsInFolder(folder_id,
          page * 20, 20);
        if (!o_list.ok) {
          console.error(folder_id, "ERR", o_list.msg);
          break;
        }
        let LAST_DATE = new Date("2020-03-27")
        if (o_list.data.files.length) {
          let first_one_date = new Date(o_list.data.files[0].mtime * 1000);
          if (first_one_date.valueOf() < LAST_DATE.valueOf()) {
            break
          }
          // debugger
          for (let item of o_list.data.files) {
            if (item.ftype == "file") {
              if (item.fsize > 100) {
                debugger
                console.log("in folder", folder_id, "file_id=", item.id,
                  "size=", item.fsize)
              }
            } else {
              let o_r = await listLargeFile(item.id)
            }
          }
        }
        if (o_list.data.next_offset == -1) {
          break;
        }
        page++;
      }
      return resolve();
    })
  }

  debugger
})

